/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;


import DTO.usuarioDTO;
import javax.swing.*;
//import sun.security.jgss.LoginConfigImpl;
import LOGIN.*;
/**
 *
 * @author Luis Olave 10
 */
public class InicioSesion extends javax.swing.JFrame {

       /**
     * Creates new form InicioSesion
     */
    public InicioSesion() {
        initComponents();
        this.txtUsuario.setText("");
        this.txtContraseña.setText("");
        this.chkOlvidoContraseña.setSelected(false);
        this.pnlRecuperacionUsuario.setVisible(false);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
         
    }

    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        pnlCentral = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        pnlIngresoUsuario = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        btnIngresar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtContraseña = new javax.swing.JPasswordField();
        chkOlvidoContraseña = new javax.swing.JCheckBox();
        pnlRecuperacionUsuario = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("INICIO DE SESIÓN");
        setResizable(false);

        pnlCentral.setPreferredSize(new java.awt.Dimension(380, 420));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGE/logo.JPG"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N
        jLabel2.setText("INICIO DE SESIÓN");

        pnlIngresoUsuario.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "INGRESO DE USUARIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Century Gothic", 1, 12), java.awt.Color.blue)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        jLabel3.setText("USUARIO");

        jLabel4.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        jLabel4.setText("CONTRASEÑA");

        txtUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUsuarioActionPerformed(evt);
            }
        });
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });

        btnIngresar.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        btnIngresar.setText("INGRESAR");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        btnCancelar.setText("CANCELAR");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtContraseña.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtContraseñaKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout pnlIngresoUsuarioLayout = new javax.swing.GroupLayout(pnlIngresoUsuario);
        pnlIngresoUsuario.setLayout(pnlIngresoUsuarioLayout);
        pnlIngresoUsuarioLayout.setHorizontalGroup(
            pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlIngresoUsuarioLayout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlIngresoUsuarioLayout.createSequentialGroup()
                        .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                            .addComponent(txtContraseña))
                        .addGap(11, 11, 11))
                    .addGroup(pnlIngresoUsuarioLayout.createSequentialGroup()
                        .addComponent(btnIngresar)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar)))
                .addContainerGap(140, Short.MAX_VALUE))
        );
        pnlIngresoUsuarioLayout.setVerticalGroup(
            pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlIngresoUsuarioLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(pnlIngresoUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnIngresar)
                    .addComponent(btnCancelar)))
        );

        chkOlvidoContraseña.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        chkOlvidoContraseña.setText("¿ OLVIDO SU CONTRASEÑA ?");
        chkOlvidoContraseña.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkOlvidoContraseñaActionPerformed(evt);
            }
        });

        pnlRecuperacionUsuario.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "RECUPERACIÓN DE CONTRASEÑA", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Century Gothic", 1, 12), java.awt.Color.red)); // NOI18N

        jLabel5.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
        jLabel5.setText("COMUNIQUESE CON EL AREA DE SOPORTE TÉCNICO N° TEL. XXX XX XX");

        javax.swing.GroupLayout pnlRecuperacionUsuarioLayout = new javax.swing.GroupLayout(pnlRecuperacionUsuario);
        pnlRecuperacionUsuario.setLayout(pnlRecuperacionUsuarioLayout);
        pnlRecuperacionUsuarioLayout.setHorizontalGroup(
            pnlRecuperacionUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRecuperacionUsuarioLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        pnlRecuperacionUsuarioLayout.setVerticalGroup(
            pnlRecuperacionUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlRecuperacionUsuarioLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addContainerGap())
        );

        javax.swing.GroupLayout pnlCentralLayout = new javax.swing.GroupLayout(pnlCentral);
        pnlCentral.setLayout(pnlCentralLayout);
        pnlCentralLayout.setHorizontalGroup(
            pnlCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCentralLayout.createSequentialGroup()
                .addGap(104, 104, 104)
                .addComponent(chkOlvidoContraseña, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(pnlCentralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlCentralLayout.createSequentialGroup()
                        .addComponent(pnlRecuperacionUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(pnlCentralLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(40, 40, 40)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(48, 48, 48))
                    .addGroup(pnlCentralLayout.createSequentialGroup()
                        .addComponent(pnlIngresoUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        pnlCentralLayout.setVerticalGroup(
            pnlCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCentralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addComponent(pnlIngresoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkOlvidoContraseña)
                .addGap(13, 13, 13)
                .addComponent(pnlRecuperacionUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(145, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(pnlCentral);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        String universal = LOGIN.Encriptacion.getStringMessageDigest("1234", LOGIN.Encriptacion.SHA512);
        if (txtUsuario.getText().equals("") || txtContraseña.getText().equals("")) 
        {
            javax.swing.JOptionPane.showMessageDialog(null, "Ingrese usuario y/o contraseña");
        }
        else 
        {   
            
            String usuario = txtUsuario.getText();
            //String pass =txtContraseña.getText();
            String pass = LOGIN.Encriptacion.getStringMessageDigest(txtContraseña.getText(), LOGIN.Encriptacion.SHA512);
            boolean respuesta = LOGIN.Autenticacion.Login(usuario, pass);
            if (respuesta == false) 
            {
                javax.swing.JOptionPane.showMessageDialog(null, "Datos Invalidos");
                txtContraseña.setText("");
                txtUsuario.setText("");
            }
            else
            {
                usuarioDTO user = LOGIN.Autenticacion.BuscarUsuarioPorUsuario(usuario);
                if (user.getUsuario_usua().equalsIgnoreCase("admin")) 
                {
                    MenuAdministrador MenuAdmi = new MenuAdministrador(user);
                    MenuAdmi.setVisible(true);
                    InicioSesion.this.dispose();
                }
                else
                {
                     //Cambia la contraseña inicial
                    
                    if (user.getContrasena_usua().equals(universal)) 
                    {
                        javax.swing.JOptionPane.showMessageDialog(null, "Bienvenido! Este es tu primer ingreso a la Aplicacion de Garantias. \n Deberas cambiar la clave que viene por defecto");
                        String clave1 = LOGIN.Encriptacion.getStringMessageDigest(javax.swing.JOptionPane.showInputDialog("Ingresa tu nueva clave. Se sugiere numeros y letras."), LOGIN.Encriptacion.SHA512);
                        String clave2 = LOGIN.Encriptacion.getStringMessageDigest(javax.swing.JOptionPane.showInputDialog("Confirme la nueva clave"), LOGIN.Encriptacion.SHA512);
                        if (clave1.equals("") || clave2.equals("")) 
                        {
                            javax.swing.JOptionPane.showMessageDialog(null, "Debes ingresar la contraseña.");
                        }
                        else
                        {
                            if (clave1.equals(clave2)) 
                            {
                                user.setContrasena_usua(clave2);
                                if (!user.getContrasena_usua().equals(universal)) 
                                {
                                    LOGIN.Seguridad.actualizarContraseña(user);
                                    javax.swing.JOptionPane.showMessageDialog(null, "Contraseña cambiada con éxito!");
                                    txtContraseña.setText("");
                                    txtUsuario.setText("");
                                }
                                else
                                {
                                    javax.swing.JOptionPane.showMessageDialog(null, "Debes ingresar una contraseña nueva.");
                                }
                            }
                            else
                            {
                                javax.swing.JOptionPane.showMessageDialog(null, "No coinciden las contraseñas. Intentalo nuevamente..");
                            }
                        }
                        
                    }
                    else
                    {
                        if (user.getEst_usuario_usua().equalsIgnoreCase("Inactivo")) 
                        {
                            javax.swing.JOptionPane.showMessageDialog(null, "Este usuario esta como Inactivo. \n Contactarse con Administrador.");
                            txtContraseña.setText("");
                            txtUsuario.setText("");
                        }
                        else
                        {
                            MenuPrincipal venMenu = new MenuPrincipal(user);
                            venMenu.setVisible(true);
                            InicioSesion.this.dispose();  
                        }
                    }
                      
                }
                
            }    
            
        }
               
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.txtUsuario.setText("");
        this.txtContraseña.setText("");
        this.chkOlvidoContraseña.setSelected(false);
        this.pnlRecuperacionUsuario.setVisible(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void chkOlvidoContraseñaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkOlvidoContraseñaActionPerformed
        if (this.chkOlvidoContraseña.isSelected()) 
        {
            this.pnlRecuperacionUsuario.setVisible(true);
        } 
        else 
        {
            this.pnlRecuperacionUsuario.setVisible(false);
        }
    }//GEN-LAST:event_chkOlvidoContraseñaActionPerformed

    private void txtUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtUsuarioActionPerformed

    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        
        if (evt.getKeyCode() == evt.VK_ENTER){
            
            this.btnIngresarActionPerformed(null);
        }
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void txtContraseñaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContraseñaKeyPressed
        
        if (evt.getKeyCode() == evt.VK_ENTER){
            
            this.btnIngresarActionPerformed(null);
        }
    }//GEN-LAST:event_txtContraseñaKeyPressed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(InicioSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(InicioSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(InicioSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(InicioSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the form
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new InicioSesion().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JCheckBox chkOlvidoContraseña;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnlCentral;
    private javax.swing.JPanel pnlIngresoUsuario;
    private javax.swing.JPanel pnlRecuperacionUsuario;
    private javax.swing.JPasswordField txtContraseña;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
